package service

import (
	"encoding/json"

	openapi "github.com/alibabacloud-go/darabonba-openapi/client"
	ecs20140526 "github.com/alibabacloud-go/ecs-20140526/v2/client"
	util "github.com/alibabacloud-go/tea-utils/service"
	"github.com/alibabacloud-go/tea/tea"
	"github.com/relvacode/iso8601"
)

type AliService struct {
	BaseConfig
	cfg *openapi.Config
}

func (that *AliService) GetInstances() error {
	that.cfg = &openapi.Config{
		AccessKeyId:     &that.AccessKeyId,
		AccessKeySecret: &that.AccessKeySecret,
	}

	return nil
}
func (that *AliService) GetEcsInfo(extend map[string]any) map[string]any {

	that.cfg.RegionId = tea.String(extend["region_id"].(string))
	var (
		Client *ecs20140526.Client
		err    error
	)
	Client, err = ecs20140526.NewClient(that.cfg)
	if err != nil {
		return nil
	}
	InstanceIds, _ := json.Marshal([]string{extend["instance_id"].(string)})
	describeInstancesRequest := ecs20140526.DescribeInstancesRequest{
		RegionId:    that.cfg.RegionId,
		InstanceIds: tea.String(string(InstanceIds)),
	}
	runtime := &util.RuntimeOptions{}
	result, err := Client.DescribeInstancesWithOptions(&describeInstancesRequest, runtime)
	if err != nil {
		return nil
	}

	CreationTime, _ := iso8601.ParseString(*result.Body.Instances.Instance[0].CreationTime)
	ExpiredTime, _ := iso8601.ParseString(*result.Body.Instances.Instance[0].ExpiredTime)

	origin_data, _ := json.Marshal(result.Body.Instances.Instance[0])
	Info := map[string]any{
		"account_id":    extend["account_id"],
		"instance_id":   result.Body.Instances.Instance[0].InstanceId,
		"region_id":     extend["region_id"],
		"add_time":      CreationTime.Local().Format("2006-01-02 15:04:05"),
		"end_time":      ExpiredTime.Local().Format("2006-01-02 15:04:05"),
		"ip_address":    result.Body.Instances.Instance[0].EipAddress.IpAddress,
		"allocation_id": result.Body.Instances.Instance[0].EipAddress.AllocationId,
		"origin_data":   string(origin_data),
	}
	return Info
}
